<template>
  <div :id="id" :class="className" :style="{ height: height, width: width }" />
</template>

<script>
import echarts from "echarts";
import resize from "./mixins/resize";
import { getPieData } from "@/api/chart";
import { notify } from "@/utils/message";

export default {
  mixins: [resize],
  props: {
    className: {
      type: String,
      default: "chart",
    },
    id: {
      type: String,
      default: "chart",
    },
    width: {
      type: String,
      default: "200px",
    },
    height: {
      type: String,
      default: "200px",
    },
  },
  data() {
    return {
      chart: null,
    };
  },
  mounted() {
    this.initChart();
  },
  beforeDestroy() {
    if (!this.chart) {
      return;
    }
    this.chart.dispose();
    this.chart = null;
  },
  methods: {
    initChart() {
      // 获取图表容器
      this.chart = echarts.init(document.getElementById(this.id));
      // 1. 拿数据
      getPieData()
        .then((res) => {
          notify(1, "获取饼图数据");
          // 2. 绘制图表
          this.chart.setOption({
            title: {
              text: "图书类型数量分布",
              left: "center",
            },
            tooltip: {
              trigger: "item",
            },
            legend: {
              orient: "vertical",
              left: "left",
            },
            series: [
              {
                name: "图书数量分布",
                type: "pie",
                radius: ["40%", "80%"],
                avoidLabelOverlap: false,
                padAngle: 4,
                itemStyle: {
                  borderRadius: 10,
                },
                label: {
                  show: false,
                  position: "center",
                },
                emphasis: {
                  label: {
                    show: true,
                    fontSize: 30,
                    fontWeight: "bold",
                  },
                },
                labelLine: {
                  show: false,
                },
                data: res.data.data,
              },
            ],
          });
        })
        .catch((err) => {
          notify(2, "获取图表数据失败", err);
        });
    },
  },
};
</script>
